

from moviepy import VideoFileClip
import speech_recognition as sr
import tempfile
import os
import datetime
 
def extract_audio(video_path, output_path):
    video = VideoFileClip(video_path)
    audio = video.audio
    audio.write_audiofile(output_path)
    video.close()
    return output_path
 
def transcribe_audio(audio_path, language='en-US'):
    recognizer = sr.Recognizer()
    with sr.AudioFile(audio_path) as source:
        audio_data = recognizer.record(source)
    text = recognizer.recognize_google(audio_data, language=language)
    return text
 
def generate_srt(text, output_path):
    # 这里我们简单地假设整个音频为一个段落，实际应用中你可能需要分割成多个段落以匹配真实的语音段落。
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write('1\n')
        start_time = "00:00:00,000"  # 开始时间，根据实际音频长度调整
        end_time = "00:01:00,000"  # 结束时间，根据实际音频长度调整，这里仅为示例
        f.write(f'{start_time} --> {end_time}\n')
        f.write(text + '\n\n')  # 添加额外的换行符以区分不同的字幕段落
 
def main(video_path, output_srt):
    # 提取音频到临时文件
    with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_audio:
        audio_path = extract_audio(video_path, tmp_audio.name)
    
    # 转换音频为文本
    text = transcribe_audio(audio_path)
    print("Transcribed text:", text)
    
    # 生成SRT文件
    generate_srt(text, output_srt)
    print("SRT file generated:", output_srt)
    
    # 删除临时文件
    os.remove(audio_path)
 
# 使用示例
video_path = 'e:/out.mp4'
output_srt = 'e:/output.srt'
main(video_path, output_srt)